package com.ydy.data.service.impl;

import com.ydy.common.model.Role;
import com.ydy.common.util.CodeUtil;
import com.ydy.common.util.PageHelperUtils;
import com.ydy.common.vo.PageInfo;
import com.ydy.data.mapper.RoleInfoMapper;
import com.ydy.data.mapper.UserInfoMapper;
import com.ydy.data.service.RoleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RoleInfoServiceImpl implements RoleInfoService {


    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public List<Role> queryRoleInfo(Role role, PageInfo pageInfo) {
        PageHelperUtils.startPage(pageInfo);
        return roleInfoMapper.queryRoleInfo(role,pageInfo);
    }

    @Override
    public void submitRoleInfo(Role role) {
        String roleCode = role.getRoleCode();
        if(StringUtils.isEmpty(roleCode)){
            //查询
            List<Role> roleList = roleInfoMapper.queryRoleInfo(role,new PageInfo());
            if(!CollectionUtils.isEmpty(roleList)){
                throw new RuntimeException("角色名已存在,请重输!");
            }
            role.setRoleCode(CodeUtil.getCode());
            //插入
            roleInfoMapper.insertRoleInfo(role);
        }else{

            //修改
            roleInfoMapper.updateRoleInfo(role);
        }
    }

    @Override
    @Transactional
    public void deleteRoleInfo(String roleCode) {
        roleInfoMapper.deleteRoleInfo(roleCode);
        userInfoMapper.deleteUserRoleInfo(null,roleCode);
        //删除角色菜单
        roleInfoMapper.deleteRoleMenuInfo(roleCode,null);
        //删除角色权限
        roleInfoMapper.deleteRolePermissionInfo(roleCode,null);
    }
}
